package com.szrt.guanshen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class ScottEmailUtil {
	
	private static Properties p = new Properties();
	
	static{
		
		//路径：  统一找classpath / 指的是我们的源文件夹（Source Folder）
		InputStream input = ScottEmailUtil.class.getResourceAsStream("/szrtEmail.properties");
		
		try {
			p.load(input);
			System.out.println("读取资源文件成功......");
		} catch (IOException e) {
			System.out.println("读取资源文件失败......");
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送邮件
	 * @param to          收件人
	 * @param subject     邮件的标题
	 * @param text        邮件的内容
	 * @throws Exception  
	 */
	public static void sendEmail(String to,String subject,String text) throws Exception{
		//from 发件人电子邮箱
		String from =p.getProperty("from");
		
		//指定发送的主机 smtp.qq.com
		String host = p.getProperty("host");
		
		
		//获取系统属性
		Properties properties = System.getProperties();
		
		//设置邮件服务器
		properties.setProperty(p.getProperty("mail.smtp.host"), host);
		
		String xx =p.getProperty(p.getProperty("mail.smtp.ssl.enable"));
		
		properties.put(xx, p.getProperty("true"));
		properties.put(p.getProperty("mail.smtp.auth"), p.getProperty("true"));
		
		//获取默认session对象
		Session session = Session.getDefaultInstance(properties,new Authenticator(){
			public PasswordAuthentication getPasswordAuthentication(){
				//发件人邮箱和密码  失效  优化...  qq  163  263
				return new PasswordAuthentication(p.getProperty("from"),p.getProperty("password"));
			}
		});
		
		//创建默认的MimeMessage 对象
		MimeMessage message = new MimeMessage(session);
		
		//Set From:头部头字段
		message.setFrom(new InternetAddress(from));
		
		//Set To:头部头字段
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		
		//Set Subject:头部头字段
		message.setSubject(subject);
		
		//设置消息体
		message.setText(text);
		
		//发送消息
		Transport.send(message);
		System.out.println("Send message successfully....");
	}

}
